<?php

/**
 * @copyright (c) 2011
 */
App::uses('AppModel', 'Model');

class BankFailedLogin extends AppModel {

    var $name = 'BankFailedLogin';

    public function save($data = null,$validate = true, $fieldList = array()) {
        $s = $this->sanitize($data);
        return parent::save($s);
    }

    function addFailedLogin($username = null, $ip_addr = null) {
        $save = array(
            'username' => $username,
            'ip_addr' => $ip_addr
        );
        $result = $this->save($save);
        if ($result) {
            //Disable the account after 3 trials
            $trial_count = $this->getLoginFailedAttempts($username);
            if($trial_count >= 3){
                $modObj = ClassRegistry::init('BankUser');
                $result = $modObj->updateAll(
                    array('BankUser.active' => "'Disabled'",'BankUser.bg_color' => "'tr_red'"),
                    array('BankUser.username' => $username)
                );
            }
            return array('status' => 0, 'msg' => 'Saved!');
        } else {
            return array('status' => 1, 'msg' => 'Not Saved!');
        }
    }

    function getLoginFailedAttempts($username = null, $ip_addr = null) {
        //$sql = 'SELECT COUNT(1) AS failed FROM failed_logins WHERE attempted > DATE_SUB(NOW(), INTERVAL 15 minute)';
        $result = $this->find('count', array(
            //'conditions' => array('username' => $username, 'created > '=> 'date_sub(now(), interval 10 minute)'),
            'conditions' => array('username' => $username, 'created LIKE'=> date('Y-m-d').'%'),
            'recursive' => -1
        ));
        return $result;
    }
}